﻿#region Imports

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using N2;
using N2.Edit.Web;

#endregion

namespace AWS.N2CMS.Tags
{
    public partial class Tagged : EditPage
    {
        protected Tag SelectedTag
        {
            get
            {
                var idString = Request["selected"];
                if (!string.IsNullOrEmpty(idString))
                {
                    int id;
                    if (int.TryParse(idString, out id))
                    {
                        return N2.Context.Persister.Get<Tag>(id);
                    }
                }
                return null;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var tag = SelectedTag;
            if (tag == null)
            {
                Response.Redirect("~/N2/Plugins/Tags/Manage.aspx");
            }
            var groups = new List<TagGroup>();
            foreach (var taggedItem in tag.TaggedItems)
            {
                var groupName = N2.Context.Current.Definitions.GetDefinition(taggedItem.GetType()).Title;
                if (!groups.Any(x => x.GroupName.Equals(groupName)))
                {
                    groups.Add(new TagGroup(groupName));
                }
                groups.Single(x => x.GroupName == groupName).Tagged.Add(taggedItem);
            }
            rptrTaggedGroups.DataSource = groups;
            rptrTaggedGroups.DataBind();
        }

        protected void rptrTaggedGroups_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var group = e.Item.DataItem as TagGroup;
            var gvTagged = e.Item.FindControl("gvTagged") as GridView;
            gvTagged.DataSource = group.Tagged;
            gvTagged.DataBind();
        }
    }

    public class TagGroup
    {
        public TagGroup(string groupName)
        {
            GroupName = groupName;
            Tagged = new List<ContentItem>();
        }

        public string GroupName { get; set; }
        public IList<ContentItem> Tagged { get; set; }
    }
}